import React, { Component } from 'react'
import u from './index.module.css'
import { Input, Select, DatePicker, Button, Table, Tag, Modal, Radio, Popconfirm, message, Cascader } from 'antd'


import cityArea from '../../static/cityArea.json'
import getday from '../../util/getday'
import axios from 'axios'
message.config({
  maxCount: 1
})
const { Option } = Select;
const { RangePicker } = DatePicker;
export default class UserList extends Component {

  state = {
    newUser: '',
    list: [],
    columns: [
      {
        title: '编号',
        dataIndex: 'userid',
        key: 'userid',
        align: 'center',
        render: (value, item, key) => {
          return key + 1
        }
      },
      {
        title: '用户姓名',
        dataIndex: 'name',
        key: 'name',
        align: 'center'
      },
      {
        title: '是否初始密码',
        dataIndex: 'pwd',
        key: 'pwd',
        align: 'center',
        render: (value, item) => {
          return item.isTrue === 'true' ? '是' : '否'
        }
      }, {
        title: '最近登录日期',
        dataIndex: 'loginTime',
        key: 'loginTime',
        align: 'center',
        render: (value) => {
          return value === null ? '/' : getday(value * 1)
        }
      }, {
        title: '创建日期',
        dataIndex: 'createTime',
        key: 'createTime',
        render: (value) => {
          return getday(value * 1)
        },
        align: 'center'
      }, {
        title: '操作',
        dataIndex: 'userid',
        key: 'userid',
        render: (value, item) => {
          return <div>
            {
              item.userName === localStorage.user || item.userName === 'admin' ? null : <Tag onClick={() => this.editShowModal(item)} color="processing" >编辑</Tag>
            }
            {
              item.userName === localStorage.user || item.userName === 'admin' ? null : <Popconfirm
                title="是否确认冻结？"
                onConfirm={() => this.confirm(value)}
                onCancel={this.cancel}
                okText="确定"
                cancelText="取消"
              >
                <a href="#"><Tag>冻结</Tag></a>
              </Popconfirm>
            }

          </div>
        }
      },
    ],
    visible: false,
    pwd: '',
    role: [],
    roleid: '',
    status: '启用',
    userName: '',
    editVisible: false,
    options: null,
    user: '1', //用户账号
    name: '',//姓名
    paw: '',//密码
    address: '',//地址
    sex: '男',//性别
    age: '',//年龄
    phone: '',//手机号
    userid: null,//userid
    bjStatus: '',//编辑状态
    jobTime: '',//工作时间
    bjRoleid: '',//编辑role
    newAddress: '',
    newUserName: '',
    selcetvalue: '全部',
    startTime: '',
    endTime: '',
  }
  // 重置密码
  cz = () => {
    var arr = '123456789qwertyuiopasdfghjklzxcvbnm'
    var b = ''
    for (var i = 0; i < 6; i++) {
      let a = Math.floor(Math.random() * 35)
      b += arr[a]
    }
    console.log(b)
    this.setState({ paw: b })
  }
  // 已冻结
  confirm = userid => {

    // 用户冻结
    this.$httpReq(this.$api.userIco({ userid }), res => {
      message.success('已确认');
      this.timeUpDate()
    })
  }
  //已取消
  cancel = () => {
    message.error('已取消');
  }
  //打开添加账号
  showModal = () => {
    this.setState({
      visible: true,
    });
  };
  //关闭添加账号
  hideModal = () => {

    this.setState({ userName: '', roleid: '' })

    this.setState({
      visible: false,
    });
  };
  USERNAME = (a) => {
    message.error(a);
  }
  // 确认添加账号
  hideOk = () => {
    // onkeyup = "value=value.replace(/[^\a-\z\A-\Z\d;,.&!@#$%^*()_+\=\- ]/g,'')"
    const { pwd, userName, roleid, status, list, newUser } = this.state
    let obj = {
      pwd,
      userName,
      roleid,
      status: status === '启用' ? 'ok' : 'freeze',
      name: newUser
    }
    let index = list.findIndex(item => item.userName === userName)
    if (index !== -1) {
      let a = '该账号已存在'
      this.USERNAME(a)
      return
    }
    if (/^[a-zA-Z]{6,12}$/.test(userName) === false) {
      let a = '账号必须为字母,长度要求六到十二位字符'
      this.USERNAME(a)
      return
    }
    if (obj.name === '') {
      let a = '姓名不能为空'
      this.USERNAME(a)
      return
    }
    if (obj.roleid === '') {
      let a = '角色不能为空'
      this.USERNAME(a)
      return
    }
    // 添加数据成功
    this.$httpReq(this.$api.addUser(obj), res => { this.timeUpDate() })
    this.setState({
      visible: false,
    });
    // 刷新
    // window.history.go(0)
    this.setState({ userName: '', roleid: '' })
  }
  componentDidMount() {
    this.timeUpDate()

    this.$httpReq(this.$api.roleList(), res => {
      // console.log(res.data)
      this.setState({ role: res.data.roleData })
    })
    this.asd()
  }
  // 实时更新数据
  timeUpDate = () => {
    this.$httpReq(this.$api.userList(), res => {

      let a = res.data.sort((a, b) => b.createTime * 1 - a.createTime * 1)

      this.setState({ list: res.data })
    })
  }
  // 随机生成8位密码
  paw = () => {
    var str = '0123456789qwertyuiopasdfghjklzxcvbnm'
    var a = ''
    for (var i = 0; i < 6; i++) {
      let num = Math.floor(Math.random() * 36)
      a += str[num]
    }
    this.setState({ pwd: a })
  }
  // 添加账号
  add = () => {
    this.showModal()
    this.paw()
  }

  // 编辑
  editShowModal = (item) => {
    let obj = {
      userid: item.userid
    }
    axios.post('/user/getSetUser', obj).then(res => {
      if (!res.data.code) {
        this.USERNAME(res.data.msg)
        return
      }
      this.setState({
        editVisible: true,
      });
      const { userName, pwd, name, address, sex, age, phone, userid, roleid, status, jobTime } = res.data.data[0]

      this.setState({ user: userName, paw: pwd, name, address, sex, age, phone, userid, bjRoleid: roleid, bjStatus: status === 'ok' ? '启用' : '禁用', jobTime })

    })

    // this.$httpReq(this.$api.getSetUser(obj), res => {
    //  })


  };
  // 果真
  editHandleOk = e => {
    const { userid, paw, bjRoleid, bjStatus, name, age, sex, phone, jobTime, newAddress } = this.state

    if (name == '') {
      message.error('姓名不能为空')
      return
    }
    if (sex === null || sex === '') {
      message.error('性别为必选项')
      return
    }

    if (!/^(?:[1-9][0-9]?|1[01][0-9]|120)$/.test(age)) {
      message.error('年龄为数字类型必须小于120')
      return
    }
    if (!(/^1[3456789]\d{9}$/.test(phone))) {
      // alert("手机号码有误，请重填");
      message.error('手机格式有误')
      return false;
    }
    let obj = {
      userid,
      pwd: paw,
      roleid: bjRoleid, name, age, sex, phone, address: newAddress, jobTime,
      status: bjStatus === '启用' ? 'ok' : 'freeze'
    }
    if (obj.name === '') {
      let a = '名字不能为空'
      this.USERNAME(a)
      return
    }
    this.$httpReq(this.$api.setUser(obj), res => {
      this.timeUpDate()
      this.setState({
        newAddress: []
      })
    })
    this.setState({

      editVisible: false,
    });
  };
  editHandleCancel = e => {
    this.setState({
      editVisible: false,
    });
  };

  onChange = (value) => {
    // console.log(value);
  }
  // 用户列表搜索功能
  search = () => {
    const { newUserName, selcetvalue, startTime, endTime } = this.state
    console.log(startTime)
    let obj = {
      name: newUserName,
      type: selcetvalue === '全部' ? '' : selcetvalue === '创建日期' ? 'createTime' : 'loginTime',
      startTime,
      endTime
    }
    this.$httpReq(this.$api.searchUserList(obj), res => {
      this.setState({ list: res.data })
    })
    this.setState({ startTime: '', newUserName: '' })
  }
  render() {
    const { newAddress, newUser, selcetvalue, newUserName, bjRoleid, bjStatus, columns, list, pwd, role, status, userName, options, user, name, paw, jobTime, address, sex, age, phone, startTime } = this.state

    return <div>
      <div className={u.u_top}>
        <div className={u.u_top_one}>
          <p>姓名检索 :</p>
          <Input value={newUserName} onChange={e => this.setState({ newUserName: e.target.value })} style={{ width: 200, marginTop: '10px' }} placeholder="请输入姓名" />
        </div>
        <div className={u.u_top_two}>
          <p style={{ width: 100 }}>日期检索 :</p>
          <Select
            style={{ width: 170, marginTop: '8px' }}
            placeholder="请选择"
            optionFilterProp="children"
            value={selcetvalue}
            onChange={e => this.setState({ selcetvalue: e })}
          >   <Option value="全部">全部</Option>
            <Option value="创建日期">创建日期</Option>
            <Option value="最近登录">最近登录</Option>
          </Select>
        </div>
        <div>
          <RangePicker style={{ width: '100%', height: '30px', marginTop: '8px' }}
            onChange={e => this.setState({ startTime: e[0]._d.getTime(), endTime: e[1]._d.getTime() })} showTime={{ format: 'HH:mm' }}
          />
        </div>
        <div className={u.u_top_button}>
          <Button type="primary" onClick={() => this.search()}>搜索</Button>
        </div>
      </div>
      <div className={u.u_add}>
        <button onClick={() => this.add()}>添加账号</button>
      </div>
      <div>
        <Table pagination={{ pageSize: 6 }} dataSource={list} columns={columns} rowKey={item => item.userid} />
      </div>
      <Button type="primary" onClick={this.showModal}>
      </Button>
      {/* 添加账号 */}
      <Modal
        title="添加账号"
        visible={this.state.visible}
        onOk={this.hideOk}
        onCancel={this.hideModal}
        okText="确认"
        cancelText="取消"
      >
        <p className={u.u_p}>
          <span className={u.u_span}>账号</span>
          <Input placeholder="请输入账号" className={u.inp} style={{ width: 300 }} value={userName} onChange={e => this.setState({ userName: e.target.value })} />
        </p>
        <div className={u.u_p} >
          <span className={u.u_span}>初始密码</span>
          <p value={pwd} onChange={e => this.setState({ pwd: e.target.value })}>{pwd}</p>
        </div>
        <div className={u.u_p} >
          <span className={u.u_span}>用户姓名</span>
          <Input placeholder="请输入姓名" style={{ width: 300 }} value={newUser} className={u.inp} onChange={e => this.setState({ newUser: e.target.value })} />
        </div>
        <div className={u.u_p}>
          <span className={u.u_span}>角色</span>
          <Select
            className={u.inp}
            style={{ width: 300 }}
            placeholder="请选择角色"
            optionFilterProp="children"
            onChange={e => this.setState({ roleid: e })}
          >
            {
              role.map((item, key) => {
                return <Option key={key} value={item.roleid}>{item.roleName}</Option>
              })
            }
          </Select>
        </div>
        <div className={u.u_status}>
          <span className={u.u_span}>状态</span>
          <Radio.Group onChange={e => this.setState({ status: e.target.value })} name="radio" defaultValue={status} className={u.inp} style={{ lineHeight: '50px' }}>
            <Radio value={'启用'}>启用</Radio>
            <Radio value={'禁用'}>禁用</Radio>
          </Radio.Group>
        </div>
      </Modal>
      {/* 编辑 */}
      <Modal
        title="编辑"
        visible={this.state.editVisible}
        onOk={this.editHandleOk}
        onCancel={this.editHandleCancel}
        okText="确认"
        cancelText="取消"
      >
        <div className={u.adit_one}>
          <p>账号</p>
          <div>{user}</div>
        </div>
        <div className={u.adit_one}>
          <p>密码</p>
          <div style={{ width: 242 }}>{paw}</div>
          <p onClick={() => this.cz()} style={{ width: 60 }} className={u.cz}>重置</p>
        </div>
        <div className={u.adit_one}>
          <p>姓名</p>
          <Input placeholder="请编辑姓名" value={name} onChange={e => this.setState({ name: e.target.value })} style={{ width: 240, height: 30, marginTop: '5px' }} />
        </div>
        <div className={u.adit_one} >
          <p>性别</p>
          <Select value={sex} onChange={e => this.setState({ sex: e === '男' ? '男' : '女' })} style={{ width: 240, marginTop: '5px' }} >
            <Option value="男">男</Option>
            <Option value="女">女</Option>
          </Select>
        </div>
        <div className={u.adit_one} >
          <p>年龄</p>
          <Input placeholder="请输入年龄" value={age} onChange={e => this.setState({ age: e.target.value })} style={{ width: 240, marginTop: '5px' }} />
        </div>
        <div className={u.adit_one} >
          <p>手机号</p>
          <Input placeholder="请输入手机号" value={phone} onChange={e => this.setState({ phone: e.target.value })} style={{ width: 240, marginTop: '5px' }} />
        </div>
        <div className={u.adit_one} >
          <p>地址</p>
          <Cascader value={newAddress} options={options} onChange={(e) => { this.setState({ newAddress: e }) }} placeholder={address ? address : '请选择地址'} style={{ marginTop: '5px', width: 240 }} />
        </div>
        <div className={u.adit_one} >
          <p>工作时间</p>
          <DatePicker
            onChange={(e) => this.setState({ jobTime: e._d.getTime() })}
            style={{ width: 240, height: 35, marginTop: '5px' }} placeholder={jobTime ? getday(jobTime * 1) : '请选择时间'} />
        </div>
        <div className={u.adit_one} >
          <p>角色</p>
          <Select
            value={bjRoleid}
            onChange={e => this.setState({ bjRoleid: e })}
            style={{ width: 240, marginTop: '5px' }} >
            {
              role.map((item, key) => {
                return <Option key={key} value={item.roleid}>{item.roleName}</Option>
              })
            }
          </Select>
        </div>
        <div className={u.adit_one}>
          <p className={u.u_span} style={{ marginTop: '4px' }}>状态</p>
          <Radio.Group onChange={e => this.setState({ bjStatus: e.target.value })} name="radio" value={bjStatus} style={{ lineHeight: '30px', marginTop: '8px' }}>
            <Radio value={'启用'}>启用</Radio>
            <Radio value={'禁用'}>禁用</Radio>
          </Radio.Group>
        </div>
      </Modal>
    </div>
  }
  //地址
  asd = () => {
    let arr = []
    cityArea.forEach(item => {
      let iobj = {};
      iobj.value = item.name
      iobj.label = item.name
      iobj.children = []
      arr.push(iobj)
      item.city.forEach(jtem => {
        let jobj = {};
        jobj.value = jtem.name
        jobj.label = jtem.name
        jobj.children = []
        iobj.children.push(jobj)
        jtem.area.forEach(atem => {
          let aobj = {};
          aobj.value = atem
          aobj.label = atem
          jobj.children.push(aobj)
        })
      })

    })
    this.setState({ options: arr })
  }

}












